import json
import re
# from django.conf import settings
from django.conf import settings
from fdfs_client.client import Fdfs_client

from requests import Response
from rest_framework import serializers
from rest_framework.views import APIView
import json
from django.contrib.auth import login, authenticate
from django import http

from django.http import JsonResponse, HttpResponseRedirect

from django.views import View

from Ten_times.settings import dev
from user.models import User

from rest_framework_jwt.settings import api_settings


class UserListView(View):
    '''用户名注册'''

    def post(self, request):

        json_bytes = request.body  # 从请求体中获取原始的JSON数据，bytes类型的
        json_str = json_bytes.decode()  # 将bytes类型的JSON数据，转成JSON字符串
        user_dict = json.loads(json_str)  # 将JSON字符串，转成python的标准字典

        username = user_dict.get('username')
        password = user_dict.get('password')
        mobile = user_dict.get('mobile')
        sms_code = user_dict.get('sms_code')

        if not all([username, password, mobile, sms_code]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数!'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})

        date = User.objects.create_user(
            username=user_dict.get('username'),
            password=user_dict.get('password'),
            # mobile=user_dict.get('mobile'),
            # avatar=user_dict.get('avatar')
        )

        from rest_framework_jwt.settings import api_settings




        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(date)
        token = jwt_encode_handler(payload)

        return JsonResponse({
            'id': date.id,
            'username': date.username,
            'mobile': date.mobile,
            'avatar': date.avatar,
            'token': token
        }, safe=False)


class LoginView(View):

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        dict = json.loads(request.body)
        username = dict.get('username')
        password = dict.get('password')

        # 2.校验(整体 + 单个)
        if not all([username, password]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.验证是否能够登录
        user = authenticate(username=username,
                            password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({'code': 400,

                                 'errmsg': '用户名或者密码错误'})

        from rest_framework_jwt.settings import api_settings




        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 8.返回json
        return JsonResponse({'id': user.id,
                             'username': user.username,
                             'mobile': user.mobile,
                             'avatar': user.avatar,
                             'token': token})



class UploadAvatarView(APIView):

    def post(self, request):
        img = request.FILES.get('img')

        if not img:
            raise serializers.ValidationError('手机图片为空')
        # 这里需要注意: 添加的路径应该为配置文件的绝对路径:
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        ret = client.upload_by_buffer(img.read())
        imgurl = ret.get('Remote file_id')
        request.user.avatar = settings.FDFS_URL + imgurl
        request.user.save()

        data = {'imgurl': settings.FDFS_URL + imgurl}

        return JsonResponse(data)


class UploadCommentView(APIView):
    def post(self, request):
        upload = request.data.get('upload')
        if not upload:
            raise serializers.ValidationError('手机图片为空')
        # 这里需要注意: 添加的路径应该为配置文件的绝对路径:
        client = Fdfs_client('Ten_times/utils/fastdfs/client.conf')
        ret = client.upload_by_buffer(upload.read())
        imgurl = ret.get('Remote file_id')
        img_url = settings.FDFS_URL + imgurl
        head = "http://127.0.0.1:8080/upload_success.html?"
        # http: // scf - python.itheima.net / upload_success.html?image_url = http: //192.168.19.131: 8888/group1/M00/00/00/rBACxl3ggw2AZ1CbAAAo5jLCaQc7273744&CKEditorFuncNum = 1
        search_str = "&CKEditorFuncNum=1"
        ret_url = head + "image_url=" + img_url + search_str
        return HttpResponseRedirect(ret_url)

